//5.状态模式典型应用之“有限状态机”
// let StateMachine = require('javascript-state-machine');

class StateMachine{
    constructor(options){
       let {init='', transitions=[], methods={}} = options;
       this.state = init;
       this.transitions = transitions;
       this.methods = methods;
       this.transitions.forEach(item=>{
           this[item.name] = function () { 
                if(this.state == item.from){
                        this.state = item.to;
                        let fn = this.methods['on'+item.name.slice(0,1).toUpperCase()+item.name.slice(1)];
                        fn && fn();
                }else{
                    throw Error('init 和 from不一致');
                }
            }
       })
    };

}
let fsm = new StateMachine({
    init: 'solid',//初始状态
    transitions: [
        {
            from:'solid',
            to:'liquid',
            name:'melt'
        },
        {
            from:'liquid',
            to:'solid',
            name:'freeze'
        }
    ],
    methods:{
        //监听状态变化事件
        onMelt:function () { 
            console.log('onMelt')
         },
         onFreeze:function () { 
            console.log('onFreeze')
         },
    }
})
fsm.melt();